<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="基于FastAPI的AI聊天应用演示">
    <meta name="theme-color" content="#3b82f6">
    <title>FastAPI AI聊天演示</title>
    <!-- 本地资源引用 -->
    <!-- 引入marked.js用于Markdown解析 -->
    <script src="/static/js/marked.min.js"></script>
    <!-- 引入highlight.js用于代码高亮 -->
    <link rel="stylesheet" href="/static/css/github.min.css">
    <script src="/static/js/highlight.min.js"></script>

    <style>
        :root {
            /* 颜色变量 */
            --primary: #3b82f6;
            --primary-hover: #2563eb;
            --primary-light: #eff6ff;
            --danger: #ef4444;
            --danger-hover: #dc2626;
            --background: #f8fafc;
            --surface: #ffffff;
            --border: #e2e8f0;
            --text-primary: #1e293b;
            --text-secondary: #64748b;
            --text-tertiary: #94a3b8;

            /* 阴影变量 */
            --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
            --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);

            /* 动画变量 */
            --transition-fast: 0.2s ease;
            --transition-normal: 0.3s ease;

            /* 尺寸变量 */
            --sidebar-width: 320px;
            --border-radius-sm: 6px;
            --border-radius-md: 8px;
            --border-radius-lg: 16px;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: var(--background);
            margin: 0;
            padding: 0;
            height: 100vh;
            overflow: hidden;
            color: var(--text-primary);
            line-height: 1.5;
        }

        .app-container {
            display: flex;
            height: 100vh;
            background: var(--background);
            position: relative;
        }

        .sidebar {
            width: var(--sidebar-width);
            background: var(--surface);
            border-right: 1px solid var(--border);
            display: flex;
            flex-direction: column;
            overflow: hidden;
            box-shadow: var(--shadow-sm);
            transition: transform var(--transition-normal);
            z-index: 10;
        }

        @media (max-width: 768px) {
            .sidebar {
                position: absolute;
                top: 0;
                left: 0;
                height: 100%;
                transform: translateX(-100%);
            }

            .sidebar.active {
                transform: translateX(0);
            }
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid var(--border);
            background: var(--surface);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 18px;
            font-weight: 600;
            color: var(--text-primary);
        }

        .logo-icon {
            width: 32px;
            height: 32px;
            background: linear-gradient(135deg, var(--primary) 0%, #764ba2 100%);
            border-radius: var(--border-radius-md);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 16px;
            box-shadow: var(--shadow-sm);
        }

        .mobile-toggle {
            display: none;
            background: none;
            border: none;
            color: var(--text-secondary);
            font-size: 24px;
            cursor: pointer;
        }

        @media (max-width: 768px) {
            .mobile-toggle {
                display: block;
            }
        }



        .assistant-section {
            padding: 20px;
            flex: 1;
            overflow-y: auto;
            scrollbar-width: thin;
            scrollbar-color: var(--text-tertiary) transparent;
        }

        .assistant-section::-webkit-scrollbar {
            width: 6px;
        }

        .assistant-section::-webkit-scrollbar-track {
            background: transparent;
        }

        .assistant-section::-webkit-scrollbar-thumb {
            background-color: var(--text-tertiary);
            border-radius: 20px;
        }

        .section-title {
            font-size: 14px;
            font-weight: 600;
            color: var(--text-secondary);
            margin-bottom: 16px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .assistant-list {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .assistant-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: var(--border-radius-md);
            cursor: pointer;
            transition: all var(--transition-fast);
            border: 1px solid transparent;
        }

        .assistant-item:hover {
            background: var(--background);
        }

        .assistant-item.active {
            background: var(--primary-light);
            border-color: var(--primary);
        }

        .assistant-item.active .assistant-icon {
            background: var(--primary);
            color: white;
        }

        .assistant-icon {
            width: 32px;
            height: 32px;
            border-radius: var(--border-radius-md);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            flex-shrink: 0;
            background: var(--background);
            transition: all var(--transition-fast);
        }

        .assistant-info {
            flex: 1;
            min-width: 0;
        }

        .assistant-name {
            font-size: 14px;
            font-weight: 500;
            color: var(--text-primary);
            margin-bottom: 2px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .assistant-desc {
            font-size: 12px;
            color: #64748b;
        }

        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: var(--surface);
            overflow: hidden;
            position: relative;
        }

        .chat-header {
            padding: 20px 24px;
            border-bottom: 1px solid var(--border);
            background: var(--surface);
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: var(--shadow-sm);
            z-index: 5;
        }

        .chat-title {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .menu-toggle {
            display: none;
            background: none;
            border: none;
            color: var(--text-secondary);
            font-size: 20px;
            cursor: pointer;
            margin-right: 12px;
        }

        @media (max-width: 768px) {
            .menu-toggle {
                display: block;
            }
        }

        .selected-model-info {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 16px;
            font-weight: 600;
            color: var(--text-primary);
        }

        .selected-model-icon {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            color: white;
            background: var(--primary);
        }

        .chat-actions {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        @media (max-width: 640px) {
            .chat-actions {
                gap: 8px;
            }
        }

        .action-btn {
            padding: 8px 16px;
            border: 1px solid var(--border);
            background: var(--surface);
            border-radius: var(--border-radius-sm);
            font-size: 14px;
            cursor: pointer;
            transition: all var(--transition-fast);
            color: var(--text-secondary);
            display: flex;
            align-items: center;
            gap: 6px;
        }

        @media (max-width: 640px) {
            .action-btn {
                padding: 6px 12px;
                font-size: 13px;
            }
        }

        .action-btn:hover {
            background: var(--background);
            border-color: var(--border);
            color: var(--text-primary);
        }

        .clear-history-btn {
            background: var(--danger);
            color: white;
            border-color: var(--danger);
        }

        .clear-history-btn:hover {
            background: var(--danger-hover);
            border-color: var(--danger-hover);
            color: white;
        }

        .clear-history-btn:disabled {
            background: var(--text-tertiary);
            border-color: var(--text-tertiary);
            cursor: not-allowed;
            opacity: 0.7;
        }

        .selector-container select {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid var(--border);
            border-radius: var(--border-radius-lg);
            font-size: 14px;
            background: var(--surface);
            cursor: pointer;
            transition: all var(--transition-normal);
            font-weight: 500;
            color: var(--text-primary);
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 12px center;
            background-size: 16px;
        }

        .selector-container select:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        .selector-container select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .selector-container {
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            padding: 16px 24px;
            border-bottom: 1px solid rgba(148, 163, 184, 0.2);
        }

        .selector-row {
            display: flex;
            gap: 12px;
            margin-bottom: 12px;
        }

        .selector-row:last-child {
            margin-bottom: 0;
        }

        .selector-label {
            font-size: 13px;
            font-weight: 600;
            color: #475569;
            margin-bottom: 6px;
            display: block;
        }



        .chat-messages {
            flex: 1;
            padding: 24px;
            overflow-y: auto;
            background: var(--background);
            scroll-behavior: smooth;
            scrollbar-width: thin;
            scrollbar-color: var(--text-tertiary) transparent;
        }

        .chat-messages::-webkit-scrollbar {
            width: 6px;
        }

        .chat-messages::-webkit-scrollbar-track {
            background: transparent;
        }

        .chat-messages::-webkit-scrollbar-thumb {
            background: var(--text-tertiary);
            border-radius: 20px;
        }

        .chat-messages::-webkit-scrollbar-thumb:hover {
            background: var(--text-secondary);
        }

        .message {
            margin-bottom: 24px;
            display: flex;
            align-items: flex-start;
            animation: messageSlideIn 0.3s ease-out;
            max-width: 90%;
        }

        @keyframes messageSlideIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .message.user {
            justify-content: flex-end;
            margin-left: auto;
        }

        .message.assistant {
            margin-right: auto;
        }

        .message-avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            margin-right: 12px;
            flex-shrink: 0;
            box-shadow: var(--shadow-sm);
            transition: transform var(--transition-fast);
        }

        .message-avatar:hover {
            transform: scale(1.05);
        }

        .message.user .message-avatar {
            background: var(--primary);
            color: white;
            margin-right: 0;
            margin-left: 12px;
            order: 2;
        }

        .message.user .message-avatar::before {
            content: '👤';
        }

        .message.assistant .message-avatar {
            background: var(--background);
            color: var(--text-secondary);
            border: 1px solid var(--border);
        }

        .message.assistant .message-avatar::before {
            content: attr(data-icon);
        }

        .message-content-wrapper {
            max-width: 100%;
            padding: 14px 18px;
            border-radius: 12px;
            font-size: 15px;
            line-height: 1.6;
            word-wrap: break-word;
            position: relative;
            box-shadow: var(--shadow-sm);
        }

        .message-content-wrapper p {
            margin-bottom: 10px;
        }

        .message-content-wrapper p:last-child {
            margin-bottom: 0;
        }

        .message.user .message-content-wrapper {
            background: var(--primary);
            color: white;
            border-bottom-right-radius: 4px;
            background-image: linear-gradient(135deg, var(--primary) 0%, var(--primary-hover) 100%);
        }

        .message.user .message-content-wrapper::before {
            content: '';
            position: absolute;
            bottom: 0;
            right: -8px;
            width: 0;
            height: 0;
            border: 8px solid transparent;
            border-left-color: var(--primary-hover);
            border-bottom: none;
            border-right: none;
        }

        .message.assistant .message-content-wrapper {
            background: var(--surface);
            color: var(--text-primary);
            border: 1px solid var(--border);
            border-bottom-left-radius: 4px;
        }

        .message.assistant .message-content-wrapper::before {
            content: '';
            position: absolute;
            bottom: 0;
            left: -8px;
            width: 0;
            height: 0;
            border: 8px solid transparent;
            border-right-color: var(--border);
            border-bottom: none;
            border-left: none;
        }

        /* 深度思考内容样式 - 引用文本样式 */
        .message.assistant .message-content.reasoning-content {
            background: var(--background);
            padding: 0;
            color: var(--text-secondary);
            position: relative;
            box-shadow: var(--shadow-sm);
            line-height: 2;
            margin-bottom: 15px;
            border-left: 3px solid var(--primary);
            border-radius: 6px;
        }

        .message.assistant .message-content.reasoning-content .reasoning-body {
            padding: 16px 20px;
        }

        .message.assistant .message-content.reasoning-content p {
            margin: 0 0 10px 0;
            line-height: 1.6;
        }

        .message.assistant .message-content.reasoning-content p:last-child {
            margin-bottom: 0;
        }

        .message.assistant .message-content.reasoning-content p:last-child {
            margin-bottom: 0;
        }

        .message.assistant .message-content.reasoning-content code {
            background: #e2e8f0;
            color: #475569;
            padding: 2px 6px;
            border-radius: 4px;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 0.9em;
            font-style: normal;
        }

        /* Markdown内容样式 */
        .message-content-wrapper h1, .message-content-wrapper h2, .message-content-wrapper h3,
        .message-content-wrapper h4, .message-content-wrapper h5, .message-content-wrapper h6 {
            margin: 12px 0 8px 0;
            font-weight: 600;
            line-height: 1.3;
        }

        .message-content-wrapper h1 { font-size: 1.5em; }
        .message-content-wrapper h2 { font-size: 1.3em; }
        .message-content-wrapper h3 { font-size: 1.1em; }

        .message-content-wrapper p {
            margin: 8px 0;
            line-height: 1.6;
        }

        .message-content-wrapper ul, .message-content-wrapper ol {
            margin: 8px 0;
            padding-left: 20px;
        }

        .message-content-wrapper li {
            margin: 4px 0;
            line-height: 1.5;
        }

        .message-content-wrapper blockquote {
            margin: 12px 0;
            padding: 8px 16px;
            border-left: 4px solid #667eea;
            background: rgba(102, 126, 234, 0.05);
            border-radius: 0 8px 8px 0;
        }

        .message-content-wrapper code {
            background: rgba(102, 126, 234, 0.1);
            padding: 2px 6px;
            border-radius: 4px;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 0.9em;
        }

        .message-content-wrapper pre {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 16px;
            margin: 12px 0;
            overflow-x: auto;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 0.9em;
            line-height: 1.4;
        }

        .message-content-wrapper pre code {
            background: none;
            padding: 0;
            border-radius: 0;
        }

        .message-content-wrapper table {
            border-collapse: collapse;
            width: 100%;
            margin: 12px 0;
            font-size: 0.9em;
        }

        .message-content-wrapper th, .message-content-wrapper td {
            border: 1px solid #e5e7eb;
            padding: 8px 12px;
            text-align: left;
        }

        .message-content-wrapper th {
            background: rgba(102, 126, 234, 0.1);
            font-weight: 600;
        }

        .message-content-wrapper a {
            color: #667eea;
            text-decoration: none;
        }

        .message-content-wrapper a:hover {
            text-decoration: underline;
        }

        .message-content-wrapper hr {
            border: none;
            border-top: 2px solid rgba(102, 126, 234, 0.2);
            margin: 16px 0;
        }

        .message.assistant .message-content-wrapper::before {
            content: '';
            position: absolute;
            bottom: 0;
            left: -10px;
            width: 0;
            height: 0;
            border: 8px solid transparent;
            border-right-color: white;
            border-bottom: none;
            border-left: none;
        }

        .message.assistant .message-content-wrapper::after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: -12px;
            width: 0;
            height: 0;
            border: 10px solid transparent;
            border-right-color: rgba(102, 126, 234, 0.1);
            border-bottom: none;
            border-left: none;
        }

        /* 思考消息样式 - 沿用对话样式 */
        .thinking-message-content {
            background: white;
            color: #374151;
            border: 1px solid #e2e8f0;
            border-bottom-left-radius: 4px;
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 12px;
            font-size: 14px;
            line-height: 1.6;
            word-wrap: break-word;
            position: relative;
        }

        .thinking-message-content::before {
            content: '';
            position: absolute;
            bottom: 0;
            left: -8px;
            width: 0;
            height: 0;
            border: 8px solid transparent;
            border-right-color: #e2e8f0;
            border-bottom: none;
            border-left: none;
        }

        .thinking-message-content::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: -7px;
            width: 0;
            height: 0;
            border: 8px solid transparent;
            border-right-color: white;
            border-bottom: none;
            border-left: none;
        }

        .thinking-text {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .thinking-emoji {
            font-size: 14px;
        }

        .thinking-message {
            font-weight: normal;
        }

        .typing-dots {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            margin-left: 8px;
        }

        .typing-dots span {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: var(--primary);
            animation: typingDots 1.4s infinite ease-in-out;
        }

        .typing-dots span:nth-child(1) { animation-delay: -0.32s; }
        .typing-dots span:nth-child(2) { animation-delay: -0.16s; }
        .typing-dots span:nth-child(3) { animation-delay: 0s; }

        @keyframes typingDots {
            0%, 80%, 100% {
                transform: scale(0.8);
                opacity: 0.5;
            }
            40% {
                transform: scale(1);
                opacity: 1;
            }
        }

        .chat-input {
            background: var(--surface);
            position: relative;
            z-index: 5;
        }

        .input-container {
            position: relative;
            display: flex;
            flex-direction: column;
            background: var(--background);
            border: 1px solid var(--border);
            padding: 4px 16px;
            transition: all var(--transition-fast);
            box-shadow: var(--shadow-sm);
        }

        .enter-tip {
            position: absolute;
            right: 10px;
            bottom: -22px;
            font-size: 12px;
            color: var(--text-tertiary);
            pointer-events: none;
        }

        .input-container:focus-within {
            border-color: var(--primary);
            background: var(--surface);
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        .chat-input textarea {
            width: 100%;
            border: none;
            outline: none;
            background: transparent;
            font-size: 15px;
            color: var(--text-primary);
            resize: none;
            min-height: 80px;
            max-height: 200px;
            overflow-y: auto;
            margin-bottom: 10px;
            line-height: 1.5;
            font-family: inherit;
        }

        .chat-input textarea::placeholder {
            color: var(--text-tertiary);
        }

        .controls-section {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 5px;
        }

        .controls-section > div {
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .send-section {
            display: flex;
            justify-content: flex-end;
            width: 100%;
        }

        .controls-group {
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .image-upload-container {
            position: relative;
            display: flex;
            cursor: pointer;
            align-items: center;
            justify-content: center;
            width: 36px;
            height: 36px;
            border: 1px solid var(--border);
            border-radius: var(--border-radius-md);
            background: var(--background);
            transition: all var(--transition-fast);
        }

        .image-upload-container:hover {
            background: var(--background-hover);
            border-color: var(--border-hover);
        }

        .image-upload-btn {
            cursor: pointer;
            color: var(--text-secondary);
            font-size: 16px;
            cursor: pointer;
            transition: all var(--transition-fast);
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 100%;
            border-radius: var(--border-radius-md);
        }

        .image-upload-btn:hover {
            color: var(--primary);
            background: rgba(59, 130, 246, 0.1);
            transform: scale(1.05);
        }

        .image-upload-input {
            position: absolute;
            cursor: pointer;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }

        .image-preview {
            margin-top: 8px;
            padding: 8px;
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: var(--border-radius-md);
            display: none;
        }

        .image-preview.show {
            display: block;
        }

        .image-preview-item {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 4px;
        }

        .image-preview-thumbnail {
            width: 40px;
            height: 40px;
            object-fit: cover;
            border-radius: 4px;
            border: 1px solid var(--border);
        }

        .image-preview-info {
            flex: 1;
            font-size: 12px;
            color: var(--text-secondary);
        }

        .image-preview-remove {
            padding: 4px 8px;
            background: var(--danger);
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            transition: all var(--transition-fast);
        }

        .image-preview-remove:hover {
            background: #dc2626;
        }

        .message-image {
            max-width: 300px;
            max-height: 200px;
            border-radius: var(--border-radius-md);
            margin: 8px 0;
            cursor: pointer;
            transition: all var(--transition-fast);
        }

        .message-image:hover {
            transform: scale(1.02);
            box-shadow: var(--shadow-md);
        }

        .send-button {
            padding: 4px 12px;
            background: var(--primary);
            color: white;
            border: 1px solid var(--primary);
            border-radius: var(--border-radius-sm);
            font-size: 12px;
            font-weight: 500;
            cursor: pointer;
            transition: all var(--transition-fast);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }

        .send-button:hover {
            background: var(--primary-hover);
            border-color: var(--primary-hover);
        }

        .send-button:disabled {
            background: var(--text-tertiary);
            border-color: var(--text-tertiary);
            cursor: not-allowed;
            opacity: 0.7;
        }

        .model-selector {
            padding: 8px 12px;
            background: var(--background);
            border: 1px solid var(--border);
            border-radius: var(--border-radius-md);
            font-size: 13px;
            color: var(--text-secondary);
            cursor: pointer;
            transition: all var(--transition-fast);
            max-width: 70%;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 8px center;
            background-size: 12px;
            padding-right: 28px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        /* 自定义模型选择器样式 */
        .custom-select-wrapper {
            position: relative;
            display: flex;
            align-items: center;
            height: 36px;
            min-width: 120px;
            max-width: 200px;
        }

        .custom-select {
            display: flex;
            align-items: center;
            justify-content: flex-start;
            cursor: pointer;
            transition: all var(--transition-fast);
            position: relative;
            width: 100%;
            height: 100%;
            padding: 0 8px;
            border: 1px solid var(--border);
            border-radius: var(--border-radius-md);
            background: var(--background);
            gap: 6px;
        }

        .custom-select:hover {
            background: var(--background-hover);
            border-color: var(--border-hover);
        }

        .custom-select-icon {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 20px;
            height: 20px;
            color: var(--primary);
            font-size: 14px;
            flex-shrink: 0;
        }

        .custom-select-text {
            display: block;
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 13px;
            color: var(--text-primary);
            margin-left: 6px;
        }

        .custom-select-arrow {
            display: none;
            margin-left: auto;
            color: var(--text-tertiary);
            font-size: 12px;
            transition: transform 0.2s ease;
            cursor: pointer;
        }

        .custom-select.open .custom-select-arrow {
            transform: rotate(180deg);
        }

        .custom-select-dropdown {
            position: absolute;
            bottom: 100%;
            width: 200px;
            left: 0;
            right: 0;
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: var(--border-radius-md);
            margin-bottom: 4px;
            max-height: 300px;
            overflow-y: auto;
            z-index: 100;
            box-shadow: var(--shadow-md);
            display: none;
        }

        .custom-select-dropdown.show {
            display: block;
            animation: fadeIn 0.2s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .custom-option {
            display: flex;
            align-items: center;
            padding: 10px 12px;
            cursor: pointer;
            transition: background 0.2s ease;
            gap: 8px;
        }

        .custom-option:hover {
            background: var(--background);
        }

        .custom-option.selected {
            background: var(--primary-light);
        }

        .custom-option-icon {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background: var(--primary-light);
            color: var(--primary);
            font-size: 14px;
            flex-shrink: 0;
        }

        .custom-option-info {
            flex: 1;
            min-width: 0;
        }

        .custom-option-provider {
            font-size: 12px;
            font-weight: 500;
            color: var(--text-primary);
            margin-bottom: 2px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .custom-option-model {
            font-size: 11px;
            color: var(--text-secondary);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        /* 移动设备上的样式优化 */
        @media (max-width: 768px) {
            .custom-select-wrapper {
                max-width: 100%;
                width: 100%;
            }

            .custom-select {
                width: 100%;
                padding: 10px 14px;
            }

            .custom-option {
                padding: 12px 14px;
            }
        }

        .model-selector:hover {
            background: var(--background-hover);
            border-color: var(--border-hover);
        }

        .model-selector:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }



        /* 响应式设计 */
        @media (max-width: 768px) {
            body {
                padding: 10px;
            }

            .chat-container {
                height: 95vh;
                border-radius: var(--border-radius-xl);
                box-shadow: var(--shadow-lg);
            }

            .chat-header {
                padding: 16px;
                font-size: 18px;
            }

            .session-info {
                padding: 10px 16px;
                font-size: 12px;
                flex-direction: column;
                gap: 8px;
                align-items: flex-start;
            }

            .selector-container {
                padding: 12px 16px;
            }

            .selector-row {
                flex-direction: column;
                gap: 8px;
            }

            .chat-messages {
                padding: 16px;
            }

            .message-content-wrapper {
                max-width: 85%;
                padding: 12px 16px;
                font-size: 14px;
            }

            .chat-input {
                padding: 16px;
            }

            .controls-section {
                flex-wrap: wrap;
                gap: 8px;
                margin-bottom: 12px;
            }

            .send-section {
                margin-top: 8px;
            }

            .model-selector,
            .custom-select-wrapper {
                min-width: 100%;
                width: 100%;
                order: 1;
            }

            .custom-select {
                width: 40px;
                height: 40px;
                padding: 8px;
                font-size: 14px;
                margin-right: 8px;
            }

            .custom-select-icon {
                width: 28px;
                height: 28px;
                font-size: 16px;
            }

            .custom-select-text {
                font-size: 14px;
            }

            .send-button {
                padding: 12px 16px;
                font-size: 14px;
                flex-grow: 1;
                order: 2;
            }

            .custom-select-dropdown {
                position: fixed;
                bottom: 80px;
                left: 16px;
                right: 16px;
                max-height: 50vh;
                z-index: 1000;
            }

            .custom-option {
                padding: 14px 16px;
            }

            .custom-option-icon {
                width: 28px;
                height: 28px;
            }

            .custom-option-provider {
                font-size: 14px;
            }

            .custom-option-model {
                font-size: 12px;
            }
        }

        @media (max-width: 480px) {
            body {
                padding: 0;
            }

            .chat-container {
                height: 100vh;
                border-radius: 0;
                box-shadow: none;
            }

            .message-content-wrapper {
                max-width: 90%;
                padding: 10px 14px;
                font-size: 13px;
            }

            .chat-header {
                font-size: 16px;
            }
        }

        /* Markdown表格样式 */
        .markdown-table {
            border-collapse: collapse;
            width: 100%;
            margin: 16px 0;
            font-size: 14px;
            background: var(--surface);
            border-radius: var(--border-radius-md);
            overflow: hidden;
            box-shadow: var(--shadow-sm);
        }

        .markdown-table th,
        .markdown-table td {
            border: 1px solid var(--border);
            padding: 10px 14px;
            text-align: left;
        }

        .markdown-table th {
            background-color: var(--background);
            font-weight: 600;
            color: var(--text-primary);
        }

        .markdown-table tr:nth-child(even) {
            background-color: var(--background-alt);
        }

        .markdown-table tr:hover {
            background-color: var(--background-hover);
        }



        /* 代码块增强样式 */
        pre {
            background: var(--background);
            border: 1px solid var(--border);
            border-radius: var(--border-radius-md);
            padding: 16px;
            margin: 16px 0;
            overflow-x: auto;
            position: relative;
            box-shadow: var(--shadow-sm);
        }

        pre code {
            background: transparent;
            padding: 0;
            border: none;
            border-radius: 0;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 0.9em;
            color: var(--text-primary);
            line-height: 1.6;
        }

        /* 行内代码样式 */
        code {
            background: var(--background-alt);
            padding: 3px 6px;
            border-radius: var(--border-radius-sm);
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 0.9em;
            color: var(--primary);
            border: 1px solid var(--border);
        }

        /* 深色模式支持 */
        @media (prefers-color-scheme: dark) {
            :root {
                --surface: #1f2937;
                --background: #111827;
                --background-alt: #1e293b;
                --background-hover: #334155;
                --text-primary: #f3f4f6;
                --text-secondary: #d1d5db;
                --text-tertiary: #9ca3af;
                --border: #374151;
                --border-hover: #4b5563;
                --primary: #3b82f6;
                --primary-hover: #2563eb;
                --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.3);
                --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.4);
                --shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.5);
            }

            .chat-container {
                background: var(--surface);
                box-shadow: var(--shadow-lg);
            }

            .chat-messages {
                background: linear-gradient(135deg, var(--surface) 0%, var(--background) 100%);
            }

            .message.assistant .message-content-wrapper {
                background: var(--background-alt);
                color: var(--text-primary);
                border-color: rgba(59, 130, 246, 0.3);
            }

            .chat-input {
                background: var(--surface);
                border-top-color: var(--border);
            }

            .enter-tip {
                font-size: 11px;
                bottom: -24px;
            }

            .input-container {
                background: var(--background-alt);
                border-color: var(--border);
            }

            .chat-input textarea {
                color: var(--text-primary);
            }

            .chat-input textarea::placeholder {
                color: var(--text-tertiary);
            }

            .send-button {
                background: var(--primary);
                border-color: var(--primary);
            }

            .send-button:hover {
                background: var(--primary-hover);
                border-color: var(--primary-hover);
            }

            .model-selector {
                background: var(--background-alt);
                border-color: var(--border);
                color: var(--text-secondary);
            }

            .model-selector:hover {
                background: var(--background-hover);
                border-color: var(--border-hover);
            }

            .markdown-table {
                background: var(--background-alt);
            }

            .markdown-table th {
                background-color: var(--background);
                color: var(--text-primary);
            }

            .markdown-table td {
                border-color: var(--border);
                color: var(--text-secondary);
            }

            pre {
                background: var(--background);
                border-color: var(--border);
            }

            code {
                background: var(--background);
                color: var(--primary);
                border-color: var(--border);
            }
        }
    </style>
</head>
<body>
    <div class="app-container">
        <!-- 左侧模型选择面板 -->
        <div class="sidebar">
            <div class="sidebar-header">
                <div class="logo">
                    <div class="logo-icon">🤖</div>
                    <span>AI Chat</span>
                </div>
            </div>

            <div class="assistant-section">
                    <div class="section-title">智能助手</div>
                    <div class="assistant-list">
                        <!-- 助手列表将通过 JavaScript 动态加载 -->
                    </div>
                </div>
        </div>

        <!-- 右侧对话区域 -->
        <div class="chat-container">
            <div class="chat-header">
                <div class="chat-title">
                    <div class="selected-model-info" id="selectedModelInfo">
                        <div class="selected-model-icon">🤖</div>
                        <span>请选择模型开始对话</span>
                    </div>
                </div>
                <div class="chat-actions">
                    <button class="action-btn" onclick="startNewChat()" title="新建对话">
                        ➕ 新对话
                    </button>
                    <button class="action-btn clear-history-btn" id="clearHistoryBtn" onclick="clearHistory()" disabled title="清除历史">
                        🗑️ 清除历史
                    </button>
                </div>
            </div>

            <div class="chat-messages" id="chatMessages">
                <div class="message assistant">
                    <div class="message-avatar">🤖</div>
                    <div class="message-content-wrapper">
                        👋 欢迎使用FastAPI AI聊天演示！请从左侧选择一个AI模型开始对话。
                    </div>
                </div>
            </div>



            <div class="chat-input">
                <div class="input-container">
                    <div class="controls-section">
                        <div class="custom-select-wrapper">
                            <select id="modelSelect" class="model-selector" style="display: none;">
                                <option value="">🔄 加载模型中...</option>
                            </select>
                            <div id="customSelect" class="custom-select">
                                <div class="custom-select-icon">🤖</div>
                                <div class="custom-select-text">加载模型中...</div>
                                <div class="custom-select-arrow">▼</div>
                            </div>
                            <div id="customSelectDropdown" class="custom-select-dropdown">
                                <!-- 选项将通过JavaScript动态加载 -->
                            </div>
                        </div>
                        <div class="image-upload-container">
                            <div class="image-upload-btn">
                                <span>📷</span>
                                <input type="file" class="image-upload-input" id="imageUpload" accept="image/*" onchange="handleImageUpload(event)">
                            </div>
                        </div>
                    </div>
                    <textarea id="messageInput" placeholder="输入您的消息..." onkeypress="handleKeyPress(event)"></textarea>
                    <div class="image-preview" id="imagePreview">
                        <!-- 图片预览将在这里显示 -->
                    </div>
                    <div class="enter-tip">Enter 发送 / Ctrl Enter 换行</div>
                    <div class="send-section">
                        <button class="send-button" id="sendButton" onclick="sendMessage()">
                            发送
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentSessionId = null;
        let userId = 'demo_user_' + Math.random().toString(36).substr(2, 9);
        let availableProviders = [];
        let allModels = {};
        let selectedProvider = null;
        let selectedModel = null;
        let currentAssistantType = 'assistant'; // 当前选中的助手类型
        let currentImageData = null; // 当前选中的图片数据
        let currentImageType = null; // 当前选中的图片类型

        /**
         * 获取可用的AI提供商列表和模型信息
         */
        async function loadProviders() {
            try {
                const response = await fetch('/providers');
                const data = await response.json();
                availableProviders = data.providers;
                allModels = data.all_models || {};
                providerIcons = data.provider_icons || {};

                // 加载模型列表到选择器
                loadModelSelector();


            } catch (error) {
                console.error('加载AI提供商失败:', error);
                const modelSelect = document.getElementById('modelSelect');
                modelSelect.innerHTML = '<option value="">❌ 加载失败</option>';
            }
        }

        /**
         * 加载模型列表到选择器
         */
        function loadModelSelector() {
            const modelSelect = document.getElementById('modelSelect');
            modelSelect.innerHTML = '<option value="">请选择模型...</option>';

            // 收集所有可用模型
            availableProviders.forEach(provider => {
                if (provider.models && provider.models.length > 0) {
                    provider.models.forEach(model => {
                        const option = document.createElement('option');
                        option.value = `${provider.id}:${model}`;
                        option.textContent = `${getProviderIcon(provider.id)} ${provider.name} - ${model}`;
                        option.setAttribute('data-provider-icon', getProviderIcon(provider.id));
                        option.setAttribute('data-provider-name', provider.name);
                        option.setAttribute('data-model-name', model);
                        if (provider.is_default && !selectedProvider) {
                            option.selected = true;
                            selectedProvider = provider.id;
                            selectedModel = model;
                        }
                        modelSelect.appendChild(option);
                    });
                }
            });

            // 如果有默认选中的模型，手动触发一次change事件以更新显示
            if (selectedProvider && selectedModel) {
                const event = new Event('change');
                modelSelect.dispatchEvent(event);
            } else if (modelSelect.options.length > 1) {
                // 如果没有默认模型但有可用模型，选择第一个可用模型
                modelSelect.selectedIndex = 1;
                const event = new Event('change');
                modelSelect.dispatchEvent(event);
            }

            // 初始化自定义选择器样式
            styleModelSelector();
        }

        // 全局变量存储从后端获取的提供商图标配置
        let providerIcons = {};

        /**
         * 获取提供商图标
         */
        function getProviderIcon(providerId) {
            return providerIcons[providerId] || '🤖';
        }

        // 全局变量存储从接口获取的角色配置
        let aiRolesConfig = {};

        /**
         * 获取助手图标
         * @param {string} assistantType - 助手类型
         * @returns {string} 对应的图标
         */
        function getAssistantIcon(assistantType) {
            // 从接口配置中获取图标，如果没有则使用默认图标
            const roleConfig = aiRolesConfig[assistantType];
            if (roleConfig && roleConfig.icon) {
                return roleConfig.icon;
            }
            // 默认图标映射（作为后备）
            const defaultIcons = {
                'assistant': '🤖',
                'teacher': '👨‍🏫',
                'programmer': '👨‍💻'
            };
            return defaultIcons[assistantType] || '🤖';
        }

        /**
         * 更新所有assistant消息的头像
         * @param {string} assistantType - 助手类型
         */
        function updateAssistantAvatars(assistantType) {
            const assistantMessages = document.querySelectorAll('.message.assistant .message-avatar');
            const icon = getAssistantIcon(assistantType);

            assistantMessages.forEach(avatar => {
                avatar.setAttribute('data-icon', icon);
            });
        }





        /**
         * 选择智能助手类型
         * @param {string} assistantType - 助手类型 ('general', 'coding', 'writing', 'analysis')
         */
        function selectAssistant(assistantType) {
            // 更新当前助手类型
            currentAssistantType = assistantType;

            // 移除所有助手项的active类
            document.querySelectorAll('.assistant-item').forEach(item => {
                item.classList.remove('active');
            });

            // 为当前选中的助手添加active类
            event.target.closest('.assistant-item').classList.add('active');

            // 更新所有现有的assistant消息头像
            updateAssistantAvatars(assistantType);

            // 从全局配置中获取角色信息
            const roleConfig = aiRolesConfig[assistantType];
            if (!roleConfig) {
                console.error('未找到角色配置:', assistantType);
                return;
            }

            const config = {
                icon: roleConfig.icon || getAssistantIcon(assistantType),
                name: roleConfig.name,
                welcome: `👋 您好！我是${roleConfig.name}，${roleConfig.description}`
            };

            // 更新选中模型信息显示
            updateSelectedModelInfo(assistantType);

            // 开始新的对话会话
            startNewChat(config.welcome);


        }

        /**
         * 加载AI角色配置
         * 从后端接口获取角色列表和配置
         */
        async function loadAIRoles() {
            try {
                const response = await fetch('/roles');
                const data = await response.json();

                // 将角色数组转换为对象格式，便于查找
                 aiRolesConfig = {};
                 data.roles.forEach(role => {
                     aiRolesConfig[role.key] = {
                         name: role.name,
                         description: role.description,
                         icon: role.icon || getDefaultIcon(role.key) // 使用接口返回的图标或默认图标
                     };
                 });

                // 渲染助手列表
                renderAssistantList();

                console.log('AI角色配置加载成功:', aiRolesConfig);
            } catch (error) {
                console.error('加载AI角色配置失败:', error);
                // 使用默认配置
                aiRolesConfig = {
                    'assistant': {
                        name: '智能助手',
                        description: '友善、专业的AI助手，能够帮助用户解答各种问题',
                        icon: '🤖'
                    },
                    'teacher': {
                        name: 'AI老师',
                        description: '经验丰富的老师，擅长用简单易懂的方式解释复杂概念',
                        icon: '👨‍🏫'
                    },
                    'programmer': {
                        name: '编程专家',
                        description: '资深的程序员，精通多种编程语言和技术栈',
                        icon: '👨‍💻'
                    }
                };
                renderAssistantList();
            }
        }

        /**
         * 获取角色的默认图标
         * @param {string} roleKey - 角色键名
         * @returns {string} 默认图标
         */
        function getDefaultIcon(roleKey) {
            const iconMap = {
                'assistant': '🤖',
                'teacher': '👨‍🏫',
                'programmer': '👨‍💻'
            };
            return iconMap[roleKey] || '🤖';
        }

        /**
         * 渲染助手列表
         * 根据从接口获取的角色配置动态生成助手列表
         */
        function renderAssistantList() {
            const assistantList = document.querySelector('.assistant-list');
            if (!assistantList) return;

            assistantList.innerHTML = '';

            Object.keys(aiRolesConfig).forEach((roleKey, index) => {
                const role = aiRolesConfig[roleKey];
                const assistantItem = document.createElement('div');
                assistantItem.className = `assistant-item ${index === 0 ? 'active' : ''}`;
                assistantItem.onclick = () => selectAssistant(roleKey);

                assistantItem.innerHTML = `
                    <div class="assistant-icon">${role.icon}</div>
                    <div class="assistant-info">
                        <div class="assistant-name">${role.name}</div>
                        <div class="assistant-desc">${role.description}</div>
                    </div>
                `;

                assistantList.appendChild(assistantItem);
            });

            // 默认选择第一个助手
            const firstRoleKey = Object.keys(aiRolesConfig)[0];
            if (firstRoleKey) {
                currentAssistantType = firstRoleKey;
                updateSelectedModelInfo(firstRoleKey);
            }
        }

        /**
         * 更新选中模型信息显示
         * @param {string} assistantType - 助手类型
         */
        function updateSelectedModelInfo(assistantType) {
            const roleConfig = aiRolesConfig[assistantType];
            if (!roleConfig) return;

            const selectedModelInfo = document.getElementById('selectedModelInfo');
            if (selectedModelInfo) {
                selectedModelInfo.innerHTML = `
                    <div class="selected-model-icon">${roleConfig.icon}</div>
                    <span>${roleConfig.name}</span>
                `;
            }
        }

        /**
         * 开始新的聊天会话
         * 创建新的会话ID并初始化聊天界面
         * @param {string} welcomeMessage - 自定义欢迎消息
         */
        async function startNewChat(welcomeMessage = null) {
            try {
                const response = await fetch(`/chat/start?user_id=${userId}`, {
                    method: 'POST'
                });
                const data = await response.json();

                currentSessionId = data.session_id;
                document.getElementById('clearHistoryBtn').disabled = false;

                // 清空聊天记录
                const chatMessages = document.getElementById('chatMessages');
                chatMessages.innerHTML = '';

                // 添加欢迎消息（使用自定义消息或服务器返回的消息）
                addMessage('assistant', welcomeMessage || data.welcome_message);

                // 聚焦输入框
                document.getElementById('messageInput').focus();

            } catch (error) {
                console.error('启动聊天失败:', error);
                alert('启动聊天失败，请检查服务器连接');
            }
        }

        /**
         * 处理键盘按键事件
         * @param {KeyboardEvent} event - 键盘事件
         */
        function handleKeyPress(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
            // 自动调整文本区域高度
            setTimeout(() => {
                const textarea = event.target;
                textarea.style.height = 'auto';
                const newHeight = Math.min(textarea.scrollHeight, 200);
                textarea.style.height = newHeight + 'px';
            }, 0);
        }

        /**
         * 发送消息到AI并处理流式响应
         */
        async function sendMessage() {
            const messageInput = document.getElementById('messageInput');
            const sendButton = document.getElementById('sendButton');
            const modelSelect = document.getElementById('modelSelect');

            const message = messageInput.value.trim();
            const selectedModelValue = modelSelect.value;

            if (!message) {
                alert('请输入消息内容');
                return;
            }

            if (!selectedModelValue) {
                alert('请先选择AI模型');
                return;
            }

            // 解析选中的模型信息
            let provider = selectedProvider;
            let model = selectedModel;
            if (selectedModelValue && selectedModelValue.includes(':')) {
                [provider, model] = selectedModelValue.split(':');
            }

            // 如果没有会话，先创建会话
            if (!currentSessionId) {
                await startNewChat();
            }

            // 添加用户消息到界面（包含图片）
            if (currentImageData) {
                addMessageWithImage('user', message, currentImageData, currentImageType);
            } else {
                addMessage('user', message);
            }
            messageInput.value = '';

            let currentImageDataTmp = currentImageData
            let currentImageTypeTmp = currentImageType
            // 清除图片预览
            if (currentImageData) {
                removeImagePreview();
            }

            // 显示输入指示器
            showTypingIndicator();

            // 禁用输入
            messageInput.disabled = true;
            document.getElementById('sendButton').disabled = true;

            try {
                // 获取选中的模型信息
                const modelSelectValue = document.getElementById('modelSelect').value;
                let provider = selectedProvider;
                let model = selectedModel;

                if (modelSelectValue && modelSelectValue.includes(':')) {
                    [provider, model] = modelSelectValue.split(':');
                }

                // 构建请求体
                const requestBody = {
                    user_id: userId,
                    session_id: currentSessionId,
                    message: message,
                    provider: provider,
                    model: model,
                    image_data: currentImageDataTmp,
                    image_type: currentImageTypeTmp
                };

                // 发送POST请求获取流式响应
                const response = await fetch('/chat/stream', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(requestBody)
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();

                let reasoningMessage = '';
                let contentMessage = '';
                let messageContainer = null;
                let reasoningElement = null;
                let contentElement = null;
                let hasShownTypingIndicator = false;

                // 处理流式响应
                async function processStream() {
                    try {
                        while (true) {
                            const { done, value } = await reader.read();
                            if (done) break;

                            const chunk = decoder.decode(value, { stream: true });
                            const lines = chunk.split('\n');

                            for (const line of lines) {
                                if (line.startsWith('data: ')) {
                                    const jsonStr = line.slice(6);
                                    if (jsonStr.trim() === '') continue;

                                    try {
                                        const data = JSON.parse(jsonStr);

                                        if (data.type === 'chunk' || data.type === 'content' || data.type === 'reasoning') {
                                            if (!hasShownTypingIndicator) {
                                                // 获取思考消息元素并转换为普通消息
                                                const thinkingElement = getThinkingMessageElement();
                                                if (thinkingElement) {
                                                    hideTypingIndicator();
                                                    // 获取消息容器
                                                    messageContainer = thinkingElement.parentElement;
                                                }
                                                hasShownTypingIndicator = true;
                                            }

                                            // 如果还没有消息容器，创建一个
                                            if (!messageContainer) {
                                                messageContainer = createMessageContainer('assistant');
                                                document.getElementById('chatMessages').appendChild(messageContainer);
                                            }

                                            // 根据类型处理内容
                                            if (data.type === 'reasoning') {
                                                // 深度思考内容
                                                if (!reasoningElement) {
                                                    reasoningElement = document.createElement('div');
                                                    reasoningElement.className = 'message-content reasoning-content';

                                                    // 创建reasoning-body容器
                                                    const reasoningBody = document.createElement('div');
                                                    reasoningBody.className = 'reasoning-body';
                                                    reasoningElement.appendChild(reasoningBody);

                                                    // 将reasoning元素添加到消息容器的content wrapper中
                                                    const contentWrapper = messageContainer.querySelector('.message-content-wrapper');
                                                    contentWrapper.appendChild(reasoningElement);
                                                }
                                                reasoningMessage += data.content;

                                                // 实时渲染思考内容
                                                const reasoningBody = reasoningElement.querySelector('.reasoning-body');
                                                renderMarkdownContent(reasoningMessage, reasoningBody);
                                            } else {
                                                // 普通内容
                                                if (!contentElement) {
                                                    contentElement = document.createElement('div');
                                                    contentElement.className = 'message-content';

                                                    // 将content元素添加到消息容器的content wrapper中
                                                    const contentWrapper = messageContainer.querySelector('.message-content-wrapper');
                                                    contentWrapper.appendChild(contentElement);
                                                }
                                                contentMessage += data.content;

                                                // 实时渲染回答内容
                                                renderMarkdownContent(contentMessage, contentElement);
                                            }
                                            scrollToBottom();
                                        } else if (data.type === 'end') {
                                            // 重新启用输入
                                            messageInput.disabled = false;
                                            document.getElementById('sendButton').disabled = false;
                                            messageInput.focus();
                                            return;
                                        } else if (data.type === 'error') {
                                            hideTypingIndicator();
                                            addMessage('assistant', '❌ ' + data.content);
                                            messageInput.disabled = false;
                                            document.getElementById('sendButton').disabled = false;
                                            return;
                                        }
                                    } catch (parseError) {
                                        console.error('解析JSON失败:', parseError, 'JSON字符串:', jsonStr);
                                    }
                                }
                            }
                        }
                    } catch (error) {
                        console.error('处理流式响应失败:', error);
                        hideTypingIndicator();
                        addMessage('assistant', '❌ 抱歉，连接出现问题，请重试。');
                        messageInput.disabled = false;
                        document.getElementById('sendButton').disabled = false;
                    }
                }

                // 开始处理流式响应
                processStream();

            } catch (error) {
                console.error('发送消息失败:', error);
                hideTypingIndicator();
                addMessage('assistant', '❌ 抱歉，发送消息失败，请重试。');
                messageInput.disabled = false;
                document.getElementById('sendButton').disabled = false;
            }
        }

        /**
         * 添加包含图片的消息到聊天界面
         * @param {string} role - 消息角色
         * @param {string} content - 消息内容
         * @param {string} imageData - Base64图片数据
         * @param {string} imageType - 图片类型
         */
        function addMessageWithImage(role, content, imageData, imageType) {
            const chatMessages = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}`;

            // 创建头像
            const avatarDiv = document.createElement('div');
            avatarDiv.className = 'message-avatar';

            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content-wrapper';

            // 创建图片元素
            if (imageData) {
                const imageElement = document.createElement('img');
                imageElement.className = 'message-image';
                imageElement.src = `data:${imageType};base64,${imageData}`;
                imageElement.alt = '上传的图片';
                contentDiv.appendChild(imageElement);
            }

            // 创建文本内容
            if (content) {
                const textElement = document.createElement('div');
                textElement.className = 'message-content';
                textElement.textContent = content;
                contentDiv.appendChild(textElement);
            }

            messageDiv.appendChild(avatarDiv);
            messageDiv.appendChild(contentDiv);
            chatMessages.appendChild(messageDiv);
            scrollToBottom();

            return contentDiv;
        }

        /**
         * 添加消息到聊天界面
         * @param {string} role - 消息角色 ('user' 或 'assistant')
         * @param {string} content - 消息内容
         * @param {boolean} isReasoning - 是否为深度思考内容
         * @returns {HTMLElement} 消息内容元素
         */
        function addMessage(role, content, isReasoning = false) {
            const chatMessages = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}`;

            // 创建头像
            const avatarDiv = document.createElement('div');
            avatarDiv.className = 'message-avatar';

            // 如果是assistant消息，设置当前助手类型的图标
            if (role === 'assistant') {
                const icon = getAssistantIcon(currentAssistantType);
                avatarDiv.setAttribute('data-icon', icon);
            }

            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content-wrapper';

            // 如果是深度思考内容，添加特殊样式和结构
            if (isReasoning) {
                contentDiv.classList.add('reasoning-content');

                // 创建reasoning-body容器
                const reasoningBody = document.createElement('div');
                reasoningBody.className = 'reasoning-body';

                // 渲染思考内容
                if (role === 'assistant') {
                    renderMarkdownContent(content, reasoningBody);
                } else {
                    reasoningBody.textContent = content;
                }

                contentDiv.appendChild(reasoningBody);
            } else {
                // 普通内容处理
                if (role === 'assistant') {
                    renderMarkdownContent(content, contentDiv);
                } else {
                    contentDiv.textContent = content;
                }
            }

            messageDiv.appendChild(avatarDiv);
            messageDiv.appendChild(contentDiv);
            chatMessages.appendChild(messageDiv);

            scrollToBottom();
            return contentDiv;
        }

        // 思考文本数组
        const thinkingMessages = [
            'AI正在思考',
            '正在分析您的问题',
            '正在组织语言',
            '正在查找相关信息',
            '正在生成回答',
            '马上就好'
        ];

        let thinkingInterval = null;
        let thinkingMessageIndex = 0;
        let thinkingMessageElement = null;

        /**
         * 显示AI思考指示器
         * 创建一个assistant消息来显示思考状态
         */
        function showTypingIndicator() {
            const chatMessages = document.getElementById('chatMessages');

            // 创建思考消息元素
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message assistant';
            messageDiv.id = 'thinkingIndicatorMessage';

            const avatarDiv = document.createElement('div');
            avatarDiv.className = 'message-avatar';
            const icon = getAssistantIcon(currentAssistantType);
            avatarDiv.setAttribute('data-icon', icon);

            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content-wrapper thinking-message-content';

            // 创建思考内容
            const thinkingContent = document.createElement('div');
            thinkingContent.className = 'thinking-text';
            thinkingContent.innerHTML = `
                <span class="thinking-emoji">🤔</span>
                <span class="thinking-message" id="currentThinkingText">${thinkingMessages[0]}</span>
                <div class="typing-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
            `;

            contentDiv.appendChild(thinkingContent);
            messageDiv.appendChild(avatarDiv);
            messageDiv.appendChild(contentDiv);
            chatMessages.appendChild(messageDiv);

            thinkingMessageElement = messageDiv;

            // 重置思考文本索引
            thinkingMessageIndex = 0;

            // 开始思考文本循环
            thinkingInterval = setInterval(() => {
                thinkingMessageIndex = (thinkingMessageIndex + 1) % thinkingMessages.length;
                const currentThinkingText = document.getElementById('currentThinkingText');
                if (currentThinkingText) {
                    currentThinkingText.textContent = thinkingMessages[thinkingMessageIndex];
                }
            }, 2000);

            scrollToBottom();
        }

        /**
         * 隐藏AI思考指示器
         * 将思考消息转换为普通消息容器，而不是删除它
         */
        function hideTypingIndicator() {
            // 清除思考文本循环
            if (thinkingInterval) {
                clearInterval(thinkingInterval);
                thinkingInterval = null;
            }

            // 将思考消息转换为普通消息容器
            if (thinkingMessageElement) {
                const contentDiv = thinkingMessageElement.querySelector('.message-content-wrapper');
                if (contentDiv) {
                    // 移除思考样式，准备接收实际内容
                    contentDiv.className = 'message-content-wrapper';
                    contentDiv.innerHTML = '';
                }
                // 移除ID，避免重复
                thinkingMessageElement.removeAttribute('id');
            }
        }

        /**
         * 创建消息容器
         * @param {string} role - 消息角色 ('user' 或 'assistant')
         * @returns {HTMLElement} 消息容器元素
         */
        function createMessageContainer(role) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}`;

            // 创建头像
            const avatarDiv = document.createElement('div');
            avatarDiv.className = 'message-avatar';

            // 如果是assistant消息，设置当前助手类型的图标
            if (role === 'assistant') {
                const icon = getAssistantIcon(currentAssistantType);
                avatarDiv.setAttribute('data-icon', icon);
            }

            // 创建内容包装器
            const contentWrapper = document.createElement('div');
            contentWrapper.className = 'message-content-wrapper';

            messageDiv.appendChild(avatarDiv);
            messageDiv.appendChild(contentWrapper);

            return messageDiv;
        }

        /**
         * 获取当前的思考消息元素
         * @returns {HTMLElement|null} 思考消息的内容元素
         */
        function getThinkingMessageElement() {
            if (thinkingMessageElement) {
                const contentDiv = thinkingMessageElement.querySelector('.message-content-wrapper');
                return contentDiv;
            }
            return null;
        }

        /**
         * 清除思考消息引用
         */
        function clearThinkingMessageReference() {
            thinkingMessageElement = null;
        }



        /**
         * 增强的Markdown内容渲染函数
         * @param {string} content - 要渲染的内容
         * @param {HTMLElement} element - 目标元素
         */
        function renderMarkdownContent(content, element) {
            // 检测是否包含Markdown格式
            const hasMarkdown = content.includes('```') ||
                               content.includes('**') ||
                               content.includes('##') ||
                               content.includes('- ') ||
                               content.includes('1. ') ||
                               content.includes('|'); // 表格

            if (hasMarkdown) {
                try {
                    // Markdown 渲染
                    element.innerHTML = marked.parse(content);

                    // 代码高亮
                    element.querySelectorAll('pre code').forEach((block) => {
                        hljs.highlightElement(block);
                    });

                    // 表格样式优化
                    element.querySelectorAll('table').forEach((table) => {
                        table.className = 'markdown-table';
                    });

                } catch (error) {
                    console.warn('Markdown渲染失败，使用纯文本显示:', error);
                    element.textContent = content;
                }
            } else {
                element.textContent = content;
            }
        }

        /**
         * 滚动聊天区域到底部
         */
        function scrollToBottom() {
            const chatMessages = document.getElementById('chatMessages');
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        /**
         * 清除当前会话的对话历史
         */
        async function clearHistory() {
            if (!currentSessionId) {
                alert('没有活动的会话');
                return;
            }

            if (!confirm('确定要清除当前会话的对话历史吗？此操作不可撤销。')) {
                return;
            }

            try {
                const response = await fetch(`/chat/history/${currentSessionId}?user_id=${userId}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                     // 清除前端显示的消息
                     document.getElementById('chatMessages').innerHTML = '';
                     addMessage('assistant', '✅ 对话历史已清除，您可以开始新的对话了。');
                } else {
                    const error = await response.json();
                    alert('清除失败: ' + (error.detail || '未知错误'));
                }
            } catch (error) {
                console.error('清除历史时出错:', error);
                alert('清除失败: ' + error.message);
            }
        }



        // 模型切换提示
        document.getElementById('modelSelect').addEventListener('change', function() {
            // 更新选中的提供商和模型
            if (this.value && this.value.includes(':')) {
                [selectedProvider, selectedModel] = this.value.split(':');

                // 更新自定义选择器显示
                updateCustomSelectDisplay();

                // 只有在会话已存在时才添加切换提示消息
                if (currentSessionId) {
                    const modelName = this.options[this.selectedIndex].text;
                    addMessage('assistant', `🔄 已切换到${modelName}，我将以新的模型为您服务。`);
                }
            }
        });

        /**
         * 初始化自定义选择器样式和功能
         */
        function styleModelSelector() {
            const modelSelect = document.getElementById('modelSelect');
            const customSelect = document.getElementById('customSelect');
            const customSelectIcon = customSelect.querySelector('.custom-select-icon');
            const customSelectDropdown = document.getElementById('customSelectDropdown');

            // 初始化下拉选项
            updateCustomSelectOptions();

            // 更新显示的选中项
            updateCustomSelectDisplay();

            // 点击自定义选择器时显示/隐藏下拉菜单
            customSelect.addEventListener('click', function(e) {
                e.stopPropagation();
                customSelect.classList.toggle('open');
                customSelectDropdown.classList.toggle('show');
            });

            // 点击页面其他地方时关闭下拉菜单
            document.addEventListener('click', function() {
                customSelect.classList.remove('open');
                customSelectDropdown.classList.remove('show');
            });

            // 阻止下拉菜单的点击事件冒泡
            customSelectDropdown.addEventListener('click', function(e) {
                e.stopPropagation();
            });
        }

        /**
         * 更新自定义选择器的选项
         */
        function updateCustomSelectOptions() {
            const modelSelect = document.getElementById('modelSelect');
            const customSelectDropdown = document.getElementById('customSelectDropdown');

            // 清空现有选项
            customSelectDropdown.innerHTML = '';

            // 为每个选项创建自定义选项元素
            Array.from(modelSelect.options).forEach((option, index) => {
                if (!option.value) {
                    // 跳过空值选项（如"请选择模型..."）
                    return;
                }

                const customOption = document.createElement('div');
                customOption.className = 'custom-option';
                if (option.selected) {
                    customOption.classList.add('selected');
                }

                const providerIcon = option.getAttribute('data-provider-icon') || '🤖';
                const providerName = option.getAttribute('data-provider-name') || '';
                const modelName = option.getAttribute('data-model-name') || '';

                customOption.innerHTML = `
                    <div class="custom-option-icon">${providerIcon}</div>
                    <div class="custom-option-info">
                        <div class="custom-option-provider">${providerName}</div>
                        <div class="custom-option-model">${modelName}</div>
                    </div>
                `;

                // 点击选项时更新选择器和触发change事件
                customOption.addEventListener('click', function() {
                    // 先设置选中状态
                    modelSelect.selectedIndex = index;

                    // 更新所有选项的选中状态
                    Array.from(customSelectDropdown.querySelectorAll('.custom-option')).forEach((opt, i) => {
                        if (i === index - 1) { // 减1是因为跳过了第一个空选项
                            opt.classList.add('selected');
                        } else {
                            opt.classList.remove('selected');
                        }
                    });

                    // 触发原生select的change事件
                    const event = new Event('change');
                    modelSelect.dispatchEvent(event);

                    // 关闭下拉菜单
                    document.getElementById('customSelect').classList.remove('open');
                    customSelectDropdown.classList.remove('show');
                });

                customSelectDropdown.appendChild(customOption);
            });
        }

        /**
         * 更新自定义选择器显示的内容
         */
        function updateCustomSelectDisplay() {
            const modelSelect = document.getElementById('modelSelect');
            const customSelect = document.getElementById('customSelect');
            const customSelectIcon = customSelect.querySelector('.custom-select-icon');
            const customSelectText = customSelect.querySelector('.custom-select-text');

            if (modelSelect.selectedIndex > 0) {
                const selectedOption = modelSelect.options[modelSelect.selectedIndex];
                const providerIcon = selectedOption.getAttribute('data-provider-icon') || '🤖';
                const providerName = selectedOption.getAttribute('data-provider-name') || '';
                const modelName = selectedOption.getAttribute('data-model-name') || '';

                customSelectIcon.textContent = providerIcon;
                customSelectText.textContent = modelName || `${providerName} 模型`;
                // 设置title属性，以便鼠标悬停时显示完整信息
                customSelect.title = `${providerName} - ${modelName}`;
            } else {
                customSelectIcon.textContent = '🤖';
                customSelectText.textContent = '请选择模型...';
                customSelect.title = '请选择模型...';
            }
        }

        /**
         * 处理图片上传
         */
        async function handleImageUpload(event) {
            const file = event.target.files[0];
            if (!file) return;

            // 检查文件类型
            if (!file.type.startsWith('image/')) {
                alert('请选择图片文件');
                return;
            }

            // 检查文件大小（限制为5MB）
            if (file.size > 5 * 1024 * 1024) {
                alert('图片文件大小不能超过5MB');
                return;
            }

            try {
                // 创建FormData对象
                const formData = new FormData();
                formData.append('file', file);

                // 上传图片
                const response = await fetch('/upload/image', {
                    method: 'POST',
                    body: formData
                });

                if (response.ok) {
                    const result = await response.json();

                    // 保存图片数据
                    currentImageData = result.data.base64_data;
                    currentImageType = result.data.content_type;

                    // 显示图片预览
                    showImagePreview(file, result.data.filename);

                    console.log('图片上传成功:', result.message);
                } else {
                    const error = await response.json();
                    alert('图片上传失败: ' + (error.detail || '未知错误'));
                }
            } catch (error) {
                console.error('图片上传失败:', error);
                alert('图片上传失败: ' + error.message);
            }

            // 清空文件输入框
            event.target.value = '';
        }

        /**
         * 显示图片预览
         */
        function showImagePreview(file, filename) {
            const imagePreview = document.getElementById('imagePreview');

            // 创建预览项
            const previewItem = document.createElement('div');
            previewItem.className = 'image-preview-item';

            // 创建缩略图
            const thumbnail = document.createElement('img');
            thumbnail.className = 'image-preview-thumbnail';
            thumbnail.src = URL.createObjectURL(file);

            // 创建文件信息
            const info = document.createElement('div');
            info.className = 'image-preview-info';
            info.innerHTML = `
                <div>${filename}</div>
                <div>${(file.size / 1024).toFixed(1)} KB</div>
            `;

            // 创建删除按钮
            const removeBtn = document.createElement('button');
            removeBtn.className = 'image-preview-remove';
            removeBtn.textContent = '删除';
            removeBtn.onclick = function() {
                removeImagePreview();
            };

            // 组装预览项
            previewItem.appendChild(thumbnail);
            previewItem.appendChild(info);
            previewItem.appendChild(removeBtn);

            // 清空并添加新的预览项
            imagePreview.innerHTML = '';
            imagePreview.appendChild(previewItem);
            imagePreview.classList.add('show');
        }

        /**
         * 移除图片预览
         */
        function removeImagePreview() {
            const imagePreview = document.getElementById('imagePreview');
            imagePreview.innerHTML = '';
            imagePreview.classList.remove('show');

            // 清空图片数据
            currentImageData = null;
            currentImageType = null;
        }



        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 加载AI角色配置
            loadAIRoles();

            // 加载AI提供商列表
            loadProviders();

            // 配置marked.js选项
            if (typeof marked !== 'undefined') {
                marked.setOptions({
                    highlight: function(code, lang) {
                        if (lang && hljs.getLanguage(lang)) {
                            try {
                                return hljs.highlight(code, { language: lang }).value;
                            } catch (err) {}
                        }
                        return hljs.highlightAuto(code).value;
                    },
                    breaks: true,
                    gfm: true,
                    tables: true,
                    sanitize: false,
                    smartypants: true,
                    xhtml: true
                });
            }




        });


    </script>
</body>
</html>
